package com.mx.adapt

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding

/**
 *  @author 张孟雄
 *
 *  适配器基类
 *  只需要集成基类后重写
 *  创建Item对应的View：
 *      createItem(inflater: LayoutInflater, parent: ViewGroup, viewType: Int): View
 *  绑定数据：
 *      bindView(position: Int, binding: ViewBinding, record: T)
 *
 *
 *
 *  以下方法可选重写
 *
 *  获取对应位置的数据：
 *  getItem(position: Int)
 *
 *  获取数据总量：
 *  getItemCount()
 */
abstract class MXBaseSimpleAdapt<T>(val list: ArrayList<T> = arrayListOf()) :
    RecyclerView.Adapter<MXBaseViewHolder>() {

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    /**
     * 创建ViewHolder
     */
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MXBaseViewHolder {
        val binding = createItem(LayoutInflater.from(parent.context), parent, viewType)
        return MXBaseViewHolder(binding, viewType)
    }

    /**
     * 绑定Holder
     */
    override fun onBindViewHolder(holder: MXBaseViewHolder, position: Int) {
        val item = getItem(position) ?: return
        holder.itemView.setOnClickListener {
            itemClickCall?.invoke(position, item)
        }
        try {
            bindView(position, holder.binding, item)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 获取Item
     */
    open fun getItem(position: Int): T? = list.getOrNull(position)

    /**
     * 回去item长度
     */
    override fun getItemCount(): Int = list.size

    /**
     * 创建View
     * @param inflater
     * @param parent
     * @param viewType
     */
    abstract fun createItem(inflater: LayoutInflater, parent: ViewGroup, viewType: Int): ViewBinding

    /**
     * 绑定View
     * @param position 绑定View的位置
     */
    open fun bindView(position: Int, binding: ViewBinding, record: T) {}

    /**
     * Item点击回调
     */
    var itemClickCall: ((Int, T) -> Unit)? = null
    open fun setItemClick(click: ((position: Int, record: T) -> Unit)) {
        itemClickCall = click
    }
}
